<?php
namespace Pay\Controller;
use Common\Common\Api\Redis;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Member;
use Common\Common\Api\Redis\Product;
use Common\Common\Api\Redis\Original;
use Common\Common\Api\Redis\Websiteconfig;

class IndexController extends PayController{
    public $channel;
    public $merchants;
    private $is_inner = false;
    private $bingfa_key = "bingfa";
    private $product = null;

    //检查参数
    public function checkparams($params){
        foreach($params as $param){

        }
    }

    public function __construct(){
        $website = Websiteconfig::getInstance()->getById(1);
        if(!$website['jiaoyi']){
            $memberid = getIdByBianHao( I("request.pay_memberid",0,'intval') );
            if($memberid != 572){
                header("Content-Type:text/html; charset=utf-8");
                exit("<h1>系统正在升级中</h1>");
            }
        }

        parent::__construct();

        if(empty($_REQUEST)){
            $this->showmessage('没有数据!');
        }

        //检查参数
        $this->checkparams($_REQUEST);

        $memberid = getIdByBianHao( I("request.pay_memberid",0,'intval') );
        //商户编号
        $member_sn= I("request.pay_memberid",0,'intval');

        if(!checkRitht($memberid, 'c')){
            $this->showmessage("您的入款功能已关闭，请与系统客服联系");
        }

        //外币用户
        $website = Websiteconfig::getInstance()->getById(1);
        if($website['waibiopen']){
            $select = M("MemberWaibi")->select();
            $waibi_users = [];
            foreach($select as $k=>$v){
                $waibi_users[] = $v['mch_id'];
            }
        }else{
            $waibi_users = [];
        }

        $this->checkMember($memberid);

        $is_mobile = isMobile();

        $outid = htmlspecialchars(I("request.pay_orderid",""));
        if(M("Order")->where(array("pay_memberid"=>I("request.pay_memberid",0,'intval'),"out_trade_id"=> $outid))->find()){
            $this->showmessage('请勿重复提交订单!');
        }

        if ($memberid<=0){
            $this->showmessage("不存在的商户编号!");
        }

        $bankcode =I('request.pay_bankcode',0,'intval');
        if(!$bankcode){
            $this->showmessage('不存在的银行编码!',['pay_banckcode'=>$bankcode]);
        }

        $this->channel =M('ProductUser')->where(array("userid"=>$memberid, "pid"=>$bankcode))->find();

        $product = Product::getInstance()->getById($this->channel['pid']);

        //如果是外币用户
        if(in_array($member_sn, $waibi_users)){
            switch($bankcode){
                //微信扫码
                case 102:
                    //$product = Product::getInstance()->getById(88);
                    break;
                    //支付宝扫码
                case 101:
                    $product = Product::getInstance()->getById(90);
                    break;
                    //支付宝H5
                case 104:
                    $product = Product::getInstance()->getById(89);
                    break;
                default:
            }
        }


        $this->product = $product;

        if(!$this->channel){
            $this->showmessage("未开通此渠道",['code'=>null,'product'=>$product['name']]);
        }

        if($is_mobile){
            if(!$product['mobile']){
                $this->showmessage($product['name']."暂不支持移动端支付",['code'=>null]);
            }
        }else{
            if(!$product['pc']){
                $this->showmessage($product['name']."暂不支持PC(电脑)端支付",['code'=>null]);
            }
        }
		
		//产品是否已经关闭
        if(!in_array($member_sn, $waibi_users)) {
            if ($product['status'] != '1') {
                $this->showmessage($product['name'] . "支付产品已关闭", ['code' => null, 'product' => $product['name']]);
            }
        }


        $tails = intval($_REQUEST['pay_amount']) % 10;
        //排除尾数
        if($product['tails']){
            $tails_arr1 = explode("|", $product['tails']);
            if(in_array($tails, $tails_arr1)){
                $this->showprice($product);
            }
        }

        //固定尾数
        if($product['tails2']){
            $tails_arr2 = explode("|", $product['tails2']);
            if(!in_array($tails, $tails_arr2)){
                $this->showprice($product);
            }
        }
		
		//倍数
		if($product['bei']){
			$zhengshu = true;
			if(floatval($_REQUEST['pay_amount']) != intval($_REQUEST['pay_amount'])){
				$zhengshu = false;
			}
			
			if(!$zhengshu){
                $this->showprice($product);
			}
			
			if(intval($_REQUEST['pay_amount']) % $product['bei']){
                $this->showprice($product);
			}
		}

        if(!$product['polling']){
            $channel = Channel::getInstance()->getById($product['channel']);
            if(!$channel){
                $this->showmessage("未找到此通道的支付渠道",['code'=>null,'product'=>$product['name']]);
            }
            if($channel['status'] != '1'){
                $this->showmessage("支付渠道已关闭",['code'=>null,'product'=>$product['name']]);
            }
        }

        if($product['forbidden']){
            if(!getIPIsInChina()){
                $this->showmessage($product['name']."只支持国内IP支付",['code'=>null,'product'=>$product['name']]);
            }
        }
        if($this->channel['status'] != "1"){
            $this->showmessage("商户支付方式已关闭",['code'=>null,'product'=>$product['name']]);
        }
        if(!$this->channel){
            $this->showmessage('暂时无法连接支付服务器!',['code'=>null,'product'=>$product['name']]);
        }

        $period2 = explode("|", $product['period2']);
        if($product['low']){
            if($_REQUEST['pay_amount'] < $product['low']){
                if(!in_array($_REQUEST['pay_amount'], $period2)){
                    $this->showprice($product);
                }
            }
        }

        if($product['high']){
            if($_REQUEST['pay_amount'] > $product['high']){
                if(!in_array($_REQUEST['pay_amount'], $period2)){
                    $this->showprice($product);
                }
            }
        }

        $period = trim($product['period']);
        if($period){
            $arr = explode("|", trim($product['period']));
            $flag = false;
            foreach($arr as $k=>$v){
                if($v == $_REQUEST['pay_amount']){
                    $flag = true;
                }
            }
            if(!$flag){
                $this->showmessage($product['name']."只支持以下金额：".implode(",",$arr),['code'=>null]);
            }
        }

        //给商户制定通道
        $key = "redis_zhipai";
        $zhipai = Redis::getInstance()->get($key);
        if($zhipai){
            $bind = [
                1000032=> [
                    3 => 1133,
                    4 => 1134,
                ],
            ];
        }else{
            $bind = [];
        }

        if($product['polling']){
            switch($product['paytype']){
                case 1:
                    if(0 && in_array($member_sn, $waibi_users)){
                        $waibi_find = M("MemberWaibi")->where(['mch_id'=>$member_sn])->find();
                        if(!$waibi_find['moshi']){
                            $alipay_waibi = Product::getInstance()->getById(88);
                            $weight = $alipay_waibi['weight'];

                            $channel_id = $this->getChannel($weight,$product);
                            break;
                        }else{
                            $weixin = Product::getInstance()->getById(102);
                            //外币
                            $weixin_waibi = Product::getInstance()->getById(88);
                            $weight = $weixin['weight'] . '|'. $weixin_waibi['weight'];

                            $channel_id = $this->getChannel($weight, $product);
                            break;
                        }
                    }

                    $weight = $product['weight'];
                    $channel_id = $this->getChannel($weight,$product);
                    break;
                case 3:
                case 4:
                    //是否指定了通道
                    if(array_key_exists($member_sn, $bind)){
                        if($_REQUEST['pay_amount'] > 3000 || $_REQUEST['pay_amount'] < 200){
                            $this->showmessage($product['name']."限额200-3000,100的整数倍",['code'=>null]);
                        }

                        $channel_id = $bind[$member_sn][$product['paytype']];
                        break;
                    }

                    //直走外币
                    if(in_array($member_sn, $waibi_users)){
                        $waibi_find = M("MemberWaibi")->where(['mch_id'=>$member_sn])->find();
                        //原生支付宝
                        if($product['paytype'] == 3){
                            //原生支付宝
                            if(!$waibi_find['moshi']){
                                $alipay_waibi = Product::getInstance()->getById(90);
                                $weight = $alipay_waibi['weight'];
                            }else{
                                $alipay = Product::getInstance()->getById(101);
                                //原生支付宝
                                $alipay_origin = Product::getInstance()->getById(93);
                                //外币
                                $alipay_waibi = Product::getInstance()->getById(90);

                                $weight = $alipay['weight'] . '|' . $alipay_origin['weight'] .'|'. $alipay_waibi['weight'];
                            }

                        }else{
                            //原生支付宝H5
                            if(!$waibi_find['moshi']){
                                $alipay_waibi = Product::getInstance()->getById(89);
                                $weight = $alipay_waibi['weight'];
                            }else{
                                $alipaywap = Product::getInstance()->getById(94);
                                $alipaywap_origin = Product::getInstance()->getById(104);
                                $alipaywap_waibi = Product::getInstance()->getById(89);
                                $weight = $alipaywap['weight'] . '|' . $alipaywap_origin['weight'] .'|'. $alipaywap_waibi['weight'];
                            }
                        }

                        $channel_id = $this->getChannel($weight,$product);
                        break;
                    }


                    //是否开启了原生通道
                    $openoriginal = $website['openoriginal'];

                    //只走原生的商户
                    $member_origin_alipay = Original::getInstance()->where(['alipay'=>1]);
                    $member_origin_alipay_arr = [];
                    foreach($member_origin_alipay as $k=>$v){
                        $member_origin_alipay_arr[] = $v['mch_id'];
                    }

                    //直走普通的商户
                    $member_normal_alipay = [1000964];

                    if(in_array($member_sn, $member_origin_alipay_arr)){
                        //原生支付宝
                        if($product['paytype'] == 3){
                            //原生支付宝
                            $alipay_origin = Product::getInstance()->getById(93);
                            $weight = $alipay_origin['weight'];
                        }else{
                            //原生支付宝H5
                            $alipaywap_origin = Product::getInstance()->getById(94);
                            $weight = $alipaywap_origin['weight'];
                        }
                    }elseif(in_array($member_sn, $member_normal_alipay)){
                        //普通支付宝
                        if($product['paytype'] == 3) {
                            $alipay = Product::getInstance()->getById(101);
                            $weight = $alipay['weight'];
                        }else{
                            $alipay = Product::getInstance()->getById(104);
                            $weight = $alipay['weight'];
                        }
                    }else{
                        if($openoriginal){
                            if($product['paytype'] == 3){
                                //支付宝扫码
                                $alipay = Product::getInstance()->getById(101);
                                //原生支付宝
                                $alipay_origin = Product::getInstance()->getById(93);
                                //外币
                                //$alipay_waibi = Product::getInstance()->getById(90);

                                //$weight = $alipay['weight'] . '|' . $alipay_origin['weight'] .'|'. $alipay_waibi['weight'];
                                $weight = $alipay['weight'] . '|' . $alipay_origin['weight'];
                            }else{
                                //原生支付宝H5
                                $alipaywap = Product::getInstance()->getById(94);
                                //支付宝H5
                                $alipaywap_origin = Product::getInstance()->getById(104);
                                //支付宝H5
                                //$alipaywap_waibi = Product::getInstance()->getById(89);

                                //$weight = $alipaywap['weight'] . '|' . $alipaywap_origin['weight'] .'|'. $alipaywap_waibi['weight'];
                                $weight = $alipaywap['weight'] . '|' . $alipaywap_origin['weight'];
                            }
                        }else{
                            if($product['paytype'] == 3){
                                //支付宝扫码
                                $alipay = Product::getInstance()->getById(101);
                                $weight = $alipay['weight'];
                            }else{
                                //支付宝H5
                                $alipaywap = Product::getInstance()->getById(104);
                                $weight = $alipaywap['weight'];
                            }
                        }
                    }
                    $channel_id = $this->getChannel($weight,$product);
                    break;
                default:
                    $channel_id = $this->getChannel($product['weight'],$product);
            }

            if(!$channel_id){
                $this->showmessage("当前通道没有可用渠道");
            }

            $this->channel['api'] = $channel_id;
            $this->channel['channel'] = $channel_id;
            $c = Channel::getInstance()->getById($this->channel['channel']);
        }else{
            $this->channel['api'] = $product['channel'];
            $this->channel['channel'] = $product['channel'];

            $c = Channel::getInstance()->getById($this->channel['channel']);

            if($is_mobile){
                if(!$c['mobile']){
                    //$this->showmessage($product['name']."不支持在手机上进行支付操作",['code'=>null]);
                }
            }else{
                if(!$c['pc']){
                    //$this->showmessage($product['name']."不支持在电脑上进行支付操作",['code'=>null]);
                }
            }
        }

        if($c['high']){
            $data = date("Y-m-d",time());
            $apirun = M("Apirun")->where(array("date"=>$data,"code"=>$c['code']))->sum("money");

            if($apirun){
                if($apirun >= $c['high']){
                    //根据 $channel_id 获取通道
                    if($channel_id){
                        $channel = Channel::getInstance()->getById($channel_id);
                        if(!$channel){
                            $this->showmessage('获取系统渠道失败!',['code'=>null]);
                        }
                        $product = Product::getInstance()->find(['paytype'=>$channel['paytype']]);
                        if(!$product){
                            $this->showmessage('获取系统通道失败!',['code'=>null]);
                        }
                    }

                    $t = explode("|", $product['weight']);
                    $arr = array();
                    foreach($t as $k=>$v){
                        $tmp = explode(":", $v);
                        if($tmp[0] != $this->channel['api']){
                            $arr[] = $tmp;
                        }
                    }

                    if(empty($arr)){
                        M("Product")->where(array("id"=>$product['id']))->save(array("status"=>0,"weight"=>""));
                        Product::getInstance()->edit($product['id'], ['status'=>0,'weight'=>'']);
                    }else{
                        $str = "";
                        foreach($arr as $k=>$v){
                            $str .= implode(":",$v)."|";
                        }
                        $str = substr($str,0,-1);

                        M("Product")->where(array("id"=>$product['id']))->save(array("weight"=>$str));
                        Product::getInstance()->edit($product['id'], ['weight'=>$str]);
                    }

                    $this->showmessage('当前通道今日额度已跑满!',['code'=>null]);
                }
            }
        }
    }

    public function index(){
        if($this->channel['api']){
            $info = Channel::getInstance()->getById($this->channel['api']);

            if(!is_file(APP_PATH.'/'.MODULE_NAME.'/Controller/'.$info['code'].'Controller.class.php')){
                $this->showmessage('支付通道不存在',['pay_bankcode'=>$this->channel['api']]);
            }

            if(R($info['code'].'/Pay',[$this->channel])===FALSE){
                $this->showmessage('服务器开小差了...');
            }
        }else{
            $this->showmessage("抱歉......服务器飞去月球了");
        }
    }

    private function getChannel($weight, $product=[]){
        $is_mobile = isMobile();
        $t = explode("|", $weight);
        $arr = array();
        $i = 0;
        $android = isAndroid();
        $is_china = getIPIsInChina();
        //获取所有通道
        $channels = [];

        //Redis::getInstance()->del($this->bingfa_key);
        $bingfa = json_decode(Redis::getInstance()->get($this->bingfa_key), true);

        //echo '<pre/>'; print_r($bingfa);

        $now = date("Y-m-d H:i",time());
        if(!$bingfa || empty($bingfa)){
            $bingfa = [
                'time' => date("Y-m-d H:i", time()),
                'channel' => [],
            ];
        }else{
            if($now !== $bingfa['time']){
                $bingfa = [
                    'time' => date("Y-m-d H:i", time()),
                    'channel' => [],
                ];
            }
        }

        $zhengshu = true;
        if(floatval($_REQUEST['pay_amount']) != intval($_REQUEST['pay_amount'])){
            $zhengshu = false;
        }

        $tails = intval($_REQUEST['pay_amount']) % 10;
        $money = I("request.pay_amount",0);
        $json = I("request.pay_returntype",0,"intval");

        foreach($t as $k=>$v){
            if(!$v){
                continue;
            }
            $tmp = explode(":", $v);

            $channel_tmp = Channel::getInstance()->getById(intval($tmp[0]));

            if( $channel_tmp['bingfa'] == 0 || $channel_tmp['bingfa'] >= 50){
                $channels[] = $channel_tmp;
            }

            if(!$channel_tmp || empty($channel_tmp)){
                continue;
            }

            if($channel_tmp['bingfa']){
                if(isset($bingfa['channel'][$channel_tmp['id']])){
                    if($channel_tmp['bingfa'] <= $bingfa['channel'][$channel_tmp['id']]){
                        continue;
                    }
                }
            }

            if($channel_tmp['exceptbei']){
                if(!(intval($money) % $channel_tmp['exceptbei'])){
                    continue;
                }
            }


            //排除尾数
            if($channel_tmp['tails']){
                if(!$zhengshu){
                    continue;
                }

                $tails_arr = explode("|", $channel_tmp['tails']);
                if(!$tails_arr || empty($tails_arr)){
                    continue;
                }

                if(in_array($tails, $tails_arr)){
                    continue;
                }
            }

            if($android && $is_mobile && in_array($channel_tmp['paytype'],[3,4,17,18])){
                if(!$channel_tmp['android']){
                    continue;
                }
            }

            if($json){
                if(!$channel_tmp['json']){
                    continue;
                }
            }

            if($channel_tmp['zhengshu']){
                if(!$zhengshu){
                    continue;
                }
            }

            if($channel_tmp['fixbei']){
                if(intval($money) % $channel_tmp['fixbei']){
                    continue;
                }
            }

            if($channel_tmp['div']){
                if($zhengshu){
                    continue;
                }
            }

            if($channel_tmp['perlow'] && $channel_tmp['perlow'] > $money){
                continue;
            }
            if($channel_tmp['perhigh'] && $channel_tmp['perhigh'] < $money){
                continue;
            }

            if(!$is_china && $channel_tmp['forbidden']){
                continue;
            }

            if($is_mobile){
                if(!$channel_tmp['mobile']){
                    continue;
                }
            }else{
                if(!$channel_tmp['pc']){
                    continue;
                }
            }

            if($channel_tmp['excepts']){
                $excepts = explode("|",$channel_tmp['excepts']);
                if(in_array($money, $excepts)){
                    continue;
                }
            }

            $peroid = $channel_tmp['peroid'];
            if($peroid){
                $peroid_arr = explode("|", $peroid);

                $flag = false;
                foreach($peroid_arr as $k1=>$v1){
                    if($v1 == $money){
                        $flag = true;
                        break;
                    }
                }
                if(!$flag){
                    continue;
                }
            }

            for($j=0; $j<$tmp[1]; $j++){
                $i++;
                $arr[$tmp[0]][] = $i;
            }
        }

        if(!$i){
            //$this->showmessage("获取通道失败");
            $this->showNotFoundChannels($channels,$product);
            return false;
        }
        $rand = mt_rand(1, $i);

        $channel_id = 0;
        foreach($arr as $k=>$v){
            if(in_array($rand, $v)){
                $channel_id = $k;
                break;
            }
        }

        if(isset($bingfa['channel'][$channel_id])){
            $bingfa['channel'][$channel_id]++;
        }else{
            $bingfa['channel'][$channel_id] = 1;
        }

        Redis::getInstance()->set($this->bingfa_key, json_encode($bingfa));

        return $channel_id;
    }

    private function showNotFoundChannels($channels, $product=[]){
        $min = 0;
        $max = 0;
        $period = [];

        foreach($channels as $channel){
            if($channel['perlow'] != 0){
                if($min == 0){
                    $min = $channel['perlow'];
                }else{
                    $min = min($min,$channel['perlow']);
                }
            }else{
                if($channel['peroid']){
                    $arr = explode("|", $channel['peroid']);
                    $period = array_merge($period, $arr);
                }
            }

            if($channel['perhigh'] != 0){
                $max = max($max,$channel['perhigh']);
            }else{
                if($channel['peroid']){
                    $arr = explode("|", $channel['peroid']);
                    $period = array_merge($period, $arr);
                }
            }
        }

        if($product['period2']){
            $period2 = explode("|", $product['period2']);
        }else{
            $period2 = [];
        }
        $period = array_merge($period, $period2);

        //固定金额
        $period_str = '';
        if(!empty($period)){
            $period = array_unique($period);
            ksort($period);
            $period_str = "或者尝试以下固定金额：" . implode(",",$period);
        }

        if(!$min){
            $min = $this->product['low'];
        }

        if(!$max){
            $max = $this->product['high'];
        }

        $say = $this->product['name']."推荐提交：".$min . "到" . $max.'的金额。' . $period_str;

        $this->showmessage($say);
    }

    private function checkMember($member){
        $website = Websiteconfig::getInstance()->getById(1);

        $find = M("Member")->alias("m")
            ->join("pay_group g on m.gid=g.id","left")
            ->where(['m.id'=>$member])
            ->field("m.*,g.name as group_name")
            ->find();

        if(!$find){
            return false;
        }

        if($find['group_name'] == 'GM'){
            $this->is_inner = true;
            return true;
        }

        if($find['group_name'] == '内部人员') {
            $this->is_inner = true;
        }

        if($find['group_name'] == 'VIP') {
            $this->is_inner = true;
        }

        if(!$website['innerlimit'] && !$website['outlimit']){
            return true;
        }

        if($find['group_name'] == '内部人员'){
            if(!$website['innerlimit']){
                return true;
            }

            if($find['total'] >= $website['innerhigh']){
                $this->showmessage("超过".$find['group_name']."最高金额，请及时下发之后再进行交易！");
            }
        }else{
            if(!$website['outlimit']){
                return true;
            }

            if($find['total'] >= $website['outhigh']){
                $this->showmessage("超过".$find['group_name']."最高金额，请及时下发之后再进行交易！");
            }
        }

        return true;
    }

    private function showprice($product){
        $str = $product['name']."限额：".$product['low'] . "到" . $product['high'].'。';

        if($product['bei']){
            if($product['bei'] == 1){
                $str .= "不支持小数。";
            }else{
                $str .= "只支持支付{$product['bei']}的整数倍的金额。";
            }
        }

        //排除尾数
        if($product['tails']){
            $tails_arr1 = explode("|", $product['tails']);
            $str .= "不支持支付金额以". implode(",",$tails_arr1) ."结尾。";
        }

        //固定尾数
        if($product['tails2']){
            $tails_arr2 = explode("|", $product['tails2']);
            $str .= "只支持支付金额以". implode(",",$tails_arr2) ."结尾。";
        }

        if($product['period2']){
            $periods = explode("|", $product['period2']);
            $str .= "此通道还额外支持". implode(",",$periods) ."这些金额。";
        }

        $this->showmessage($str);
    }
}